(function () {

    $(document).ready(function () {
        var tId = 0;
        var oId = 0;

        $('.message-item').on('click', function () {

            var $this = $(this);
            var originId = $this.attr("data-originId");
            var targetId = $this.attr("data-targetId");

            tId = targetId;
            oId = originId;

            $.ajax({
                type: "POST",
                url: $('#RequestMessageURL').val(),
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ originId: originId, targetId: targetId }),
                success: function (result) {
                    var bodyContainer = $('.message-body-container');
                    bodyContainer.empty();
                    pushMessage(result);
                },
                error: function (xhr, status, msg) {
                    alert("Se ha producido un error al intentar recuperar el mensaje.");
                }
            });
        });

        $('.sendButton').on('click', function () {
            var txt = $('.chateTextBox');
            var message = txt.val();

            if (message.trim() === '') { return; }
            if (tId === 0 || oId === 0) { return; }

            $.ajax({
                type: "POST",
                url: $('#PostMessageURL').val(),
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ originId: oId, targetId: tId, message: message }),
                success: function (result) {
                    pushMessage([{ PublishedDate: undefined, Message: message, UserId: $('#UserId').val()}]);
                },
                error: function (xhr, status, msg) {
                    alert("Se ha producido un error al intentar enviar el mensaje.");
                }
            });
        });

        function pushMessage(arr) {
            var bodyContainer = $('.message-body-container');

            for (var i = 0; i < arr.length; i++) {
                var date = arr[i].PublishedDate == undefined ? new Date() : tools.parseJsonDate(arr[i].PublishedDate);
                var template = $('.messageEmptyContainerUpper').clone();
                arr[i].PublishedDate = date.formatDDMMYYYY();
                bodyContainer.append($.tmpl(template, arr[i]));
            }
        }
    });
})();